/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package netfone;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author bml
 */
public class UserDaoDB4o implements UserDao {

    ObjectContainer db;

    public UserDaoDB4o() {
        db = Db4o.openFile(Constants.USER_DIR + "/db.zambas");
    }

    public boolean saveUser(User user) {
        try {
            db.ext().set(user,2);
            
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public boolean removeUser(User user) {
        try {

            db.delete(user);

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public List<User> getUsers() {
        ObjectSet set = db.query(User.class);
        List list = getSetList(set);
        return list;

    }

    public List<User> findUser(final String searchStr) {
        Predicate predicate = new Predicate() {

            public boolean match(Object arg0) {
                User user = (User) arg0;
                return user.getName().startsWith(searchStr);

            }
        };

        ObjectSet set = db.query(predicate);
        return getSetList(set);
    }

    private List getSetList(ObjectSet set) {
        Object[] us = (Object[]) set.toArray();
        ArrayList list = new ArrayList();
        for (Object u : us) {
            list.add((User) u);
        }
        return list;
    }

    public void loadUser(User user) {
        db.commit();
        System.out.println(user.getContacts().size());
        long id = db.ext().getID(user);
        db.ext().bind(user,id);
        System.out.println(user.getContacts().size());
    }

    public List<Contact> getAllContacts() {
        return db.get(Contact.class);
    }
}
